import csv
import datetime
import os
import random

from django.conf import settings

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jiaozi.settings")

import django
import requests
django.setup()


def download_file_from_url(url, file_path):
    r = requests.get(url=url, stream=True)
    if r.status_code == 200:
        with open(file_path, 'wb') as file:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)
        return file_path
    return None


def store_file_to_qiniu(file_path, file_name):
    """
    上传文件到七牛
    :param file_path: 文件的地址
    :param file_name: 文件名称
    :return: 返回是否上传成功
    """
    from qiniu import Auth, put_file

    # 构建鉴权对象
    qiniu_auth = Auth(access_key=settings.QINIU_ACCESS_KEY, secret_key=settings.QINIU_SECRET_KEY)

    # 生成上传 Token，可以指定过期时间等
    up_token = qiniu_auth.upload_token(bucket=settings.QINIU_BUCKET_NAME, key=file_name, expires=3600)

    ret, info = put_file(up_token=up_token, key=file_name, file_path=file_path)
    print(ret, info)

    if info.status_code == 200:
        # 表示上传成功, 返回文件名
        return True
    else:
        # 上传失败
        return False


def convert_images(w_max=750):
    """
    将图片批量压缩
    """
    from product.models import ProductInfo
    from pathlib import Path
    from PIL import Image

    product_info_list = ProductInfo.objects.exclude(main_image__isnull=True).order_by('id')
    image_tmp_path = Path('media', 'tmp')
    if not image_tmp_path.exists():
        image_tmp_path.mkdir()
    for product_info in product_info_list:
        if product_info.main_image:
            old_image_url = product_info.main_image.url
            original_image_name = Path(product_info.main_image.name).name
            print('old_image_url', old_image_url)

            old_image_name = 'product_info_{}_old{}'.format(
                product_info.pk,
                Path(old_image_url).suffix
            )
            old_image_path = Path(image_tmp_path, old_image_name)

            if not Path(old_image_path).exists():
                download_file_from_url(old_image_url, old_image_path)

            if Path(old_image_path).exists():

                new_image_name = 'product_info_{}_new_{}{}'.format(
                    product_info.pk,
                    w_max,
                    Path(old_image_url).suffix
                )
                new_image_path = Path(image_tmp_path, new_image_name)

                need_update = True
                if not Path(new_image_path).exists():
                    image = Image.open(old_image_path)
                    w, h = image.size
                    if w > w_max:
                        compress_rate = w_max / w
                        img_resize = image.resize((int(w * compress_rate), int(h * compress_rate)))
                        img_resize.save(new_image_path)
                    else:
                        need_update = False

                if need_update:
                    if not original_image_name == new_image_name:
                        print(original_image_name, new_image_name)
                        store_file_to_qiniu(str(new_image_path), new_image_name)
                        product_info.main_image = str(new_image_name)
                        product_info.save()


def update_product_sales_image():
    from pathlib import Path
    from product.models import ProductSales
    ps = ProductSales.objects.all()
    for p in ps:
        print(p.pk)
        main_image = p.main_image
        if main_image:
            main_image_name = str(Path(main_image.name).name)
            if main_image_name:
                if not main_image_name.startswith('product_info_'):
                    p_main_image = str(Path(p.product_batch.product_info.main_image.name).name)
                    if p_main_image.startswith('product_info_'):
                        p.main_image = p.product_batch.product_info.main_image
                        p.save()


def update_sales():
    from sales.models import OrderItem
    ois = OrderItem.objects.filter(vip_level__isnull=True)
    for oi in ois:
        vip_levels = oi.product_sales.vip_level.all()
        if vip_levels.count() == 1:
            vip_level = vip_levels.first()
            print(oi, vip_level)
            oi.vip_level = vip_level
            oi.save()


def update_orders():
    import datetime
    from vip.models import VipSalesOrder
    current_time = datetime.datetime.now()
    vip_sales_orders = VipSalesOrder.objects.filter(
        vip_sales__vip_start__lte=current_time,
        vip_sales__vip_end__gte=current_time,
    ).order_by('pk')
    for vip_sales_order in vip_sales_orders:
        vip_sales_order.amount_used = vip_sales_order.get_amount_used()
        print('vip_sales_order', vip_sales_order.get_amount_used(), vip_sales_order)
        vip_sales_order.save()


if __name__ == '__main__':
    update_orders()
    # convert_images()
    # update_product_sales_image()
